package cn.tedu.qxhouserent.house.service.impl;

import cn.tedu.qxhouserent.commons.ex.ServiceException;
import cn.tedu.qxhouserent.commons.pojo.vo.PageData;
import cn.tedu.qxhouserent.commons.util.PageInfoToPageDataConverter;
import cn.tedu.qxhouserent.commons.web.ServiceCode;
import cn.tedu.qxhouserent.house.mapper.HouseMapper;
import cn.tedu.qxhouserent.house.mapper.UserHouseCollectionMapper;
import cn.tedu.qxhouserent.house.mapper.UserMapper;
import cn.tedu.qxhouserent.house.pojo.entity.House;
import cn.tedu.qxhouserent.house.pojo.entity.NewsDetail;
import cn.tedu.qxhouserent.house.pojo.entity.User;
import cn.tedu.qxhouserent.house.pojo.entity.UserHouseCollection;
import cn.tedu.qxhouserent.house.pojo.param.UserHouseCollectionAddNewParam;
import cn.tedu.qxhouserent.house.pojo.vo.HouseListItemVO;
import cn.tedu.qxhouserent.house.pojo.vo.HouseStandardVO;
import cn.tedu.qxhouserent.house.pojo.vo.NewsDetailStandardVO;
import cn.tedu.qxhouserent.house.service.UserHouseCollectionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static cn.tedu.qxhouserent.commons.web.ServiceCode.*;

@Service
@Slf4j
public class UserHouseCollectionImpl implements UserHouseCollectionService {

    @Autowired
    private UserHouseCollectionMapper userHouseCollectionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HouseMapper houseMapper;



    @Override
    public void addNew(UserHouseCollectionAddNewParam userHouseCollectionAddNewParam) {
        log.debug("开始处理【用户添加收藏】的业务，参数：{}", userHouseCollectionAddNewParam);
        // 检查该用户是否已收藏此房源,如果已收藏,则抛出异常
        QueryWrapper<UserHouseCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userHouseCollectionAddNewParam.getUserId())
                .eq("house_id",userHouseCollectionAddNewParam.getHouseId());
        Integer countByUsername = userHouseCollectionMapper.selectCount(queryWrapper);
        log.debug("根据用户id和房源id统计匹配的收藏数量，结果：{}", countByUsername);
        if (countByUsername > 0){
            String message = "添加收藏失败,该房源已经被收藏!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        // 检查该用户是否存在,如果不存在,则抛出异常
        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("id",userHouseCollectionAddNewParam.getUserId());
        Integer countByUsername2 = userMapper.selectCount(queryWrapper2);
        log.debug("根据用户id统计匹配的用户数量，结果：{}", countByUsername2);
        if (countByUsername2 == 0){
            String message = "添加收藏失败,用户不存在!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        // 检查该房源是否存在,如果不存在,则抛出异常
        QueryWrapper<House> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("id",userHouseCollectionAddNewParam.getHouseId());
        Integer countByUsername3 = houseMapper.selectCount(queryWrapper3);
        log.debug("根据房源id统计匹配的房源数量，结果：{}", countByUsername3);
        if (countByUsername3 == 0){
            String message = "添加收藏失败,房源不存在!";
            log.warn(message);
            throw new ServiceException(ERR_CONFLICT,message);
        }

        UserHouseCollection userHouseCollection = new UserHouseCollection();
        BeanUtils.copyProperties(userHouseCollectionAddNewParam,userHouseCollection);
        userHouseCollection.setGmtCollection(LocalDateTime.now());
        log.debug("准备将新的收藏数据写入到数据库，数据：{}", userHouseCollection);
        int rows = userHouseCollectionMapper.insert(userHouseCollection);
        if (rows != 1){
            String message = "添加收藏失败,服务器正忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ERR_INSERT,message);
        }

        //增加收藏数
        HouseStandardVO standardById = houseMapper.getStandardById(userHouseCollectionAddNewParam.getHouseId());
        if (standardById.getCollectionCount() == null) {
            String message = "数据库数据错误！";
            log.debug(message);
            throw new ServiceException(ERR_UPLOAD_INVALID_TYPE, message);
        }
        standardById.setCollectionCount(standardById.getCollectionCount() + 1L);
        House house = new House();
        BeanUtils.copyProperties(standardById, house);
        house.setGmtModified(LocalDateTime.now());
        int i = houseMapper.updateById(house);
        if (i != 1){
            String message = "修改收藏数失败,服务器正忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ERR_UPDATE,message);
        }
        log.debug("将新的收藏数据写入到数据库，完成！");


    }

    @Override
    public void deleteByUserId(Long userId, Long houseId) {
        log.debug("开始处理【通过用户id和房源id删除收藏】的业务，用户id：{},房源id: {}" ,userId,houseId);

        // 根据用户id和房源id检查收藏是否存在，如果不存在，则抛出异常
        QueryWrapper<UserHouseCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("house_id",houseId);
        int countById = userHouseCollectionMapper.selectCount(queryWrapper);
        log.debug("根据用户id和房源id统计匹配的收藏数量，结果：{}" , countById);
        if (countById==0){
            String message = "删除收藏失败，收藏数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        int rows = userHouseCollectionMapper.deleteByUserIdAndHouseId(userId, houseId);
        if (rows < 1){
            String message = "删除收藏失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ERR_DELETE, message);
        }

        //减少收藏数
        HouseStandardVO standardById = houseMapper.getStandardById(houseId);
        if (standardById.getCollectionCount() == null) {
            String message = "数据库数据错误！";
            log.debug(message);
            throw new ServiceException(ERR_UPLOAD_INVALID_TYPE, message);
        }
        standardById.setCollectionCount(standardById.getCollectionCount() - 1L);
        House house = new House();
        BeanUtils.copyProperties(standardById, house);
        house.setGmtModified(LocalDateTime.now());
        int i = houseMapper.updateById(house);
        if (i != 1){
            String message = "修改收藏数失败,服务器正忙,请稍后再试!";
            log.warn(message);
            throw new ServiceException(ERR_UPDATE,message);
        }
        log.debug("将收藏数据从数据库中删除，完成！");
    }


    @Override
    public PageData<HouseListItemVO> listHouseByUserId(Long userId, Integer pageNum) {
        Integer pageSize = 5;
        return listHouseByUserId(userId, pageNum, pageSize);
    }

    @Override
    public PageData<HouseListItemVO> listHouseByUserId(Long userId, Integer pageNum, Integer pageSize) {
        log.debug("开始处理【根据用户id查询房源列表】的业务，用户id: {},页码：{}，每页记录数：{}", userId, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<HouseListItemVO> list = houseMapper.listHouseByUserId(userId);
        PageInfo<HouseListItemVO> pageInfo = new PageInfo<>(list);
        PageData<HouseListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

    @Override
    public boolean houseCollectionInfo(Long userId, Long houseId) {
        log.debug("开始处理【判断用户是否收藏此房源】的业务,用户id: {}, 页码:{}", userId, houseId);
        QueryWrapper<UserHouseCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("house_id", houseId);
        Integer integer = userHouseCollectionMapper.selectCount(queryWrapper);
        log.debug("处理【判断用户是否收藏此房源】的业务完毕！");
        if (integer != 0) {
            return true;
        }
        return false;
    }
}
